// 云函数入口文件
const cloud = require('wx-server-sdk')
const mysql = require('mysql2/promise')
const { v4: uuidv4 } = require('uuid')

cloud.init({
  env: 'uniapp-8g0lywngd57d5c18'
})

// MySQL连接配置
const config = {
  host: 'sh-cynosdbmysql-grp-b4b8nkho.sql.tencentcdb.com',
  port: 25932,
  database: 'custom_order_management',
  user: 'root',
  password: 'jQ6w2uwY',
  // 添加连接选项
  connectTimeout: 10000, // 连接超时时间10秒
  connectionLimit: 10,   // 连接池限制
  waitForConnections: true,
  queueLimit: 0
}

// 生成不带连字符的UUID
const generateUUID = () => uuidv4().replace(/-/g, '')

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { userInfo, type, extraData } = event
  const openid = wxContext.OPENID

  let connection
  try {
    // 创建数据库连接
    connection = await mysql.createConnection(config)
    await connection.beginTransaction()

    // 如果是注册负责人
    if (type === 'manager') {
      // 生成唯一ID
      const managerId = generateUUID()

      // 先检查用户是否已经是负责人
      const [existingManagers] = await connection.execute(
        'SELECT m.* FROM member mb JOIN manager m ON mb.user_id = m.user_id WHERE mb.openid = ?',
        [openid]
      )

      if (existingManagers.length > 0) {
        throw new Error('您已经是负责人了')
      }

      // 查找现有用户记录
      const [existingUsers] = await connection.execute(
        'SELECT * FROM member WHERE openid = ?',
        [openid]
      )

      let userId
      try {
        if (existingUsers.length > 0) {
          // 如果用户已存在，使用现有用户ID
          userId = existingUsers[0].user_id
          
          // 先创建负责人记录
          await connection.execute(
            'INSERT INTO manager (manager_id, contact_info, user_id) VALUES (?, ?, ?)',
            [managerId, extraData.phone, userId]
          )

          // 然后更新用户信息
          await connection.execute(
            'UPDATE member SET user_name = ?, manager_id = ? WHERE user_id = ?',
            [extraData.name, managerId, userId]
          )
        } else {
          // 如果用户不存在，先创建用户（不设置manager_id）
          userId = generateUUID()
          await connection.execute(
            'INSERT INTO member (user_id, user_name, student_id, openid) VALUES (?, ?, ?, ?)',
            [userId, extraData.name, 'PENDING', openid]
          )

          // 创建负责人记录
          await connection.execute(
            'INSERT INTO manager (manager_id, contact_info, user_id) VALUES (?, ?, ?)',
            [managerId, extraData.phone, userId]
          )

          // 更新用户的manager_id
          await connection.execute(
            'UPDATE member SET manager_id = ? WHERE user_id = ?',
            [managerId, userId]
          )
        }

        // 提交事务
        await connection.commit()

        // 返回结果
        return {
          userId: userId,
          managerId: managerId,
          userName: extraData.name
        }
      } catch (error) {
        // 如果出错，回滚事务
        await connection.rollback()
        throw error
      }
    }
    // 如果是注册商家
    else if (type === 'merchant') {
      // 检查淘宝ID格式
      if (!/^[0-9]{9}$/.test(extraData.taobaoId)) {
        throw new Error('淘宝ID格式不正确')
      }

      // 检查该openid是否已经注册过商家
      const [existingMerchants] = await connection.execute(
        'SELECT * FROM merchant_user WHERE openid = ?',
        [openid]
      )

      if (existingMerchants.length > 0) {
        throw new Error('请勿重复注册')
      }

      // 检查商家名称是否已存在
      const [existingNames] = await connection.execute(
        'SELECT * FROM merchant_user WHERE merchant_name = ?',
        [extraData.shopName]
      )

      if (existingNames.length > 0) {
        throw new Error('该店铺名称已被使用')
      }

      // 检查淘宝ID是否已存在
      const [existingTaobao] = await connection.execute(
        'SELECT * FROM merchant_user WHERE taobao_id = ?',
        [extraData.taobaoId]
      )

      if (existingTaobao.length > 0) {
        throw new Error('该淘宝店铺已注册')
      }

      try {
        // 生成唯一ID
        const userId = generateUUID()

        // 创建商家用户记录
        await connection.execute(
          'INSERT INTO merchant_user (user_id, openid, merchant_name, taobao_id) VALUES (?, ?, ?, ?)',
          [userId, openid, extraData.shopName, extraData.taobaoId]
        )

        // 提交事务
        await connection.commit()

        // 返回结果
        return {
          userId: userId,
          merchantInfo: {
            shopName: extraData.shopName,
            taobaoId: extraData.taobaoId
          }
        }
      } catch (error) {
        // 如果出错，回滚事务
        await connection.rollback()
        throw error
      }
    }
    // 普通用户注册
    else {
      // 检查是否已经注册
      const [existingUsers] = await connection.execute(
        'SELECT * FROM member WHERE openid = ?',
        [openid]
      )

      if (existingUsers.length > 0) {
        throw new Error('该微信账号已注册')
      }

      // 生成唯一ID
      const userId = generateUUID()

      try {
        // 创建成员记录，不设置manager_id
        await connection.execute(
          'INSERT INTO member (user_id, user_name, student_id, openid) VALUES (?, ?, ?, ?)',
          [userId, userInfo.nickName, extraData.studentId || null, openid]
        )

        // 提交事务
        await connection.commit()

        // 返回结果
        return {
          userId: userId,
          userName: userInfo.nickName
        }
      } catch (error) {
        // 如果出错，回滚事务
        await connection.rollback()
        throw error
      }
    }

  } catch (error) {
    console.error('注册失败:', error)
    return {
      error: error.message
    }
  } finally {
    if (connection) {
      await connection.end()
    }
  }
} 